﻿using System.Text.RegularExpressions;

namespace MiddlewareTestWebApp
{
    public class PathParser
    {
        /// <summary>
        /// 解析出来控制器和Action
        /// 从请求路径中解析出控制器和Action
        /// 如果解析失败，返回值中的ok为false
        /// 如果请求路径为"/Test1/Save",
        /// 则 Parse 方法的返回值为 (true, "Test1", "Save")
        /// </summary>
        /// <param name="pathString"></param>
        /// <returns></returns>
        public static (bool ok, string? controllerName, string? actionName) Parse(PathString pathString)
        {
            string? path = pathString.Value;
            if (string.IsNullOrEmpty(path))
            {
                return (false, null, null);
            }
            // 解析出来控制器和Action

            // 这里使用正则表达式来解析路径
            var math = Regex.Match(path, "/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)");
            if (!math.Success)
            {
                return (false, null, null);
            }
            string controllerName = math.Groups[1].Value;
            string actionName = math.Groups[2].Value;
            return (true, controllerName, actionName);
        }
    }
}
